package org.afk.sisy.io;

import java.util.*;
import java.util.regex.*;

public class Filter
{
	private static Filter createFilter(final String filter, final boolean matchResult)
	{
		if ((filter == null) || (filter.length() == 0))
			return new Filter(matchResult);
		else
			return new Filter(filter.split(";"), matchResult);
	}

	public static Filter createExcludeFilter(final String filter)
	{
		return createFilter(filter, false);
	}

	public static Filter createIncludeFilter(final String filter)
	{
		return createFilter(filter, true);
	}

	private final boolean empty;

	private final List<String> filterList;

	private final boolean emptyResult;

	public Filter(final boolean emptyResult)
	{
		this.filterList = Collections.emptyList();
		this.emptyResult = emptyResult;
		this.empty = true;
	}

	public Filter(final String[] split, final boolean matchResult)
	{
		this.filterList = new ArrayList<String>();
		for (final String next : split)
		{
			final String prepared = prepare(next);
			if (prepared != null)
				this.filterList.add(prepared);
		}
		this.emptyResult = matchResult;
		this.empty = split.length == 0;
	}

	private String prepare(final String next)
	{
		if ((next == null) || (next.length() == 0))
			return null;
		try
		{
			Pattern.compile(next);
		}
		catch (final Exception e)
		{
			final StringBuffer buffer = new StringBuffer();
			for (final Character c : next.toCharArray())
				if (c == '*')
					buffer.append(".*");
				else if (c == '?')
					buffer.append('.');
				else if ("+()^$.{}[]|\\".indexOf(c) != -1)
					buffer.append("\\").append(c);
				else
					buffer.append(c);
			return buffer.toString();
		}
		return next;
	}

	public boolean matchAny(final String path)
	{
		if (this.empty)
			return this.emptyResult;
		for (final String filter : this.filterList)
			if (path.matches(filter) || path.contains(filter))
				return true;

		return false;
	}
}
